//
//  HomeController.m
//  JZRJAPPT
//
//  Created by mac on 16/5/8.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "HomeController.h"
#import "CenterScrollerViewSubView.h"
#import "IncomeCell.h"
#import "DayRankCell.h"
#import "LiuXSegmentView.h"
#import "MarkInManager.h"
#import "DayRankModel.h"
#import "NetWorkManager.h"
#import "ImageModel.h"
#import "DetailController.h"
#import "CPSpinnerButtonView.h"
#import "JZRJSeachBar.h"
#import "IncomeModel.h"
#import "MarketModel.h"
#import "CPMView.h"
#import "DetailViewController.h"
#import "SeachViewController.h"
#import "LoginViewController.h"
#import "SearchController.h"

@interface HomeController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,CPSpinnerButtonViewDelegate,UIScrollViewDelegate>

@property (nonatomic , strong) UIView *topView;

@property (nonatomic , strong) UIScrollView *centerScrollView;

@property (nonatomic , strong) UIView *bottomTitleView;

@property (nonatomic , strong) UIView *bottomView;

@property (nonatomic , strong) NSMutableArray *dataArray;

@property (nonatomic , strong) NSMutableArray *markArray;

@property (nonatomic , strong) NSMutableArray *imageArray;

@property (nonatomic , strong) UITableView *tableView1;

@property (nonatomic , strong) UITableView *tableView2;

@property (nonatomic,assign) CGPoint startPoint;
@property (nonatomic,assign) CGPoint endPiont;
@property (nonatomic,strong) CPSpinnerButtonView *cpsView;
@property (nonatomic,strong) JZRJSeachBar *seachView;

@property (nonatomic,strong)UITapGestureRecognizer *tapGestureRecognizer;
@end

@implementation HomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wode"] style:UIBarButtonItemStyleDone target:self action:@selector(click:)];
    
    self.seachView = [[JZRJSeachBar alloc]initWithFrame:CGRectMake(10, 10, SCREEN_WIDTH/10 *8, 30)];
    self.navigationItem.titleView = _seachView;
    self.tapGestureRecognizer =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [self.seachView addGestureRecognizer:_tapGestureRecognizer];
    
    [self loadData];
    [self markData];
    [self setLayoutViews];
    NSLog(@"%f",SCREEN_WIDTH);
}

-(void)tap:(UITapGestureRecognizer *)sender{
    
     self.hidesBottomBarWhenPushed=YES;
    SeachViewController *seachVC =[[SeachViewController alloc]init];
    //SearchController *seachVC =[[SearchController alloc]init];
    [self.navigationController pushViewController:seachVC animated:YES];
    
     self.hidesBottomBarWhenPushed=NO;
}

-(void)click:(UIBarButtonItem *)btn{
    LoginViewController *loginVC =[[LoginViewController alloc]init];
    
    [self presentViewController:loginVC animated:YES completion:nil];
    NSLog(@"123456");
}

#pragma mark 懒加载数组
- (NSMutableArray *)markArray{
    if (!_markArray ) {
        _markArray = [NSMutableArray array];
    }
    return _markArray;
}

-(void)getdata{
    
    
    [NetWorkManager getUrl1:GetMarketInfo1 paramdic:nil success:^(id data) {
        
        NSStringEncoding enc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        
        NSString *str = [[NSString alloc] initWithData:data encoding:enc];
        
        NSMutableArray *bigArray = [str componentsSeparatedByString:@";"].mutableCopy;
        [bigArray removeLastObject];
        
        NSMutableArray *nameArray = [NSMutableArray array];
        NSMutableArray *dataArray = [NSMutableArray array];
        for (NSString *s in bigArray) {
            NSString *dataStr = [[s componentsSeparatedByString:@"=\""].lastObject substringToIndex:[s componentsSeparatedByString:@"=\""].lastObject.length - 1];
            [nameArray addObject:[dataStr componentsSeparatedByString:@","].firstObject];
            NSMutableArray *da = [dataStr componentsSeparatedByString:@","].mutableCopy;
            if (da.count > 0) {
                [da removeObjectAtIndex:0];
            }
            [dataArray addObject:da];
        }
        for (int i = 0; i < nameArray.count; i++) {
            NSDictionary *dict = @{
                                   @"name":nameArray[i],
                                   @"values":dataArray[i],
                                   };
            [self.dataArray addObject:dict];
        }
        NSLog(@"%@",self.dataArray);
        //[self hahahaha];
        
        
    } error:^(id error) {
        NSLog(@"%@",error);
        
    }];

}
#pragma Mark 数据解析
-(void)loadData{
    
    [NetWorkManager getUrl:GetTodayRankList paramdic:nil success:^(id data) {
        
        NSMutableArray *dataArray = [NSMutableArray array];
        for (NSDictionary *dic in data) {
            DayRankModel *dayRankModel = [DayRankModel new];
            [dayRankModel setValuesForKeysWithDictionary:dic];
            [dataArray addObject:dayRankModel];
        }
        self.markArray = dataArray;
        [self.tableView2 reloadData];
        
    } error:^(id error) {
        NSLog(@"%@",error);
        CPMView *cpmView =[[CPMView alloc]initWithFrame:CGRectMake(100, SCREEN_HEIGHT /2, SCREEN_WIDTH - 200, 30)];
        [self.view addSubview: cpmView];
    }];
    
}

-(void)markData{
    [NetWorkManager getUrl:GetLHIncomeList paramdic:nil success:^(id data) {
        NSMutableArray *dataArray = [NSMutableArray array];
        for (NSDictionary *dic in data) {
            IncomeModel *incomeModel = [IncomeModel new];
            [incomeModel setValuesForKeysWithDictionary:dic];
            [dataArray addObject:incomeModel];
        }
        self.dataArray = dataArray;
        [self.tableView1 reloadData];
        
    } error:^(id error) {
        
    }];
}
-(void)lunboData{
    [NetWorkManager getUrl:GetHomepageImgList paramdic:nil success:^(id data) {
        
        NSMutableArray *imageArray = [NSMutableArray array];
        for (NSDictionary *dic  in data) {
            ImageModel *imageModel = [ImageModel new];
            [imageModel setValuesForKeysWithDictionary:dic];
            [imageArray addObject:imageModel];
            
        }
        self.imageArray = imageArray;
        
    } error:^(id error) {
        
        
    }];
}
#pragma mark  页面布局
- (void)setLayoutViews{
    __weak typeof(self) weakSelf = self;
    _topView = [[UIView alloc] init];
    [self.view addSubview:_topView];
    _topView.backgroundColor = [UIColor cyanColor];
    UIImageView *imageView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"banner"]];
    [_topView addSubview:imageView];
    imageView.frame = CGRectMake(0, 0,SCREEN_WIDTH ,140);
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(weakSelf.view);
        make.height.mas_equalTo(140);
    }];
    
    _centerScrollView = [[UIScrollView alloc] init];
    _centerScrollView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_centerScrollView];
    [_centerScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_topView.mas_bottom);
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_equalTo(110);
    }];
    
    
    // 设置centerScroller
    _centerScrollView.contentSize = CGSizeMake(UISCREEN_WIDTH, 110);
    
    [NetWorkManager getUrl:GetMarketInfo paramdic:nil success:^(id data) {
        NSMutableArray *dataArray = [NSMutableArray array];
        for (NSDictionary *dic in data) {
            MarketModel *marketModel = [MarketModel new];
            [marketModel setValuesForKeysWithDictionary:dic];
            [dataArray addObject:marketModel];
            
        }
        self.markArray = dataArray;
        for (int i = 0; i < self.markArray.count; i++) {
            CenterScrollerViewSubView *centerSubView = [[CenterScrollerViewSubView alloc] initWithFrame:CGRectMake(i * (UISCREEN_WIDTH / 3) + 0.5, 0, UISCREEN_WIDTH / 3 - 1, 110)];
            centerSubView.markModel = self.markArray[i];
            [_centerScrollView addSubview:centerSubView];
        }
        
    } error:^(id error) {
        NSLog(@"%@",error);
    }];
    
    UIView *segmentationView = [[UIView alloc] init];
    segmentationView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:segmentationView];
    [segmentationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_centerScrollView.mas_bottom);
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_equalTo(20);
    }];
    
    _bottomTitleView = [[UIView alloc] init];
    _bottomTitleView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_bottomTitleView];
    [_bottomTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(segmentationView.mas_bottom);
        make.left.right.bottom.equalTo(weakSelf.view);
        //make.height.mas_offset(80);
    }];
    
    // 自定义tabbleView视图
    
    self.cpsView = [[CPSpinnerButtonView alloc] initWithFrame:CGRectMake(0, 10, self.view.frame.size.width , 353)];
    self.cpsView.tintColor = [UIColor whiteColor];
    //view.tintBackgroundColor = [UIColor whiteColor];
    self.cpsView.minGap = 50;
    self.cpsView.lineHeight = 2;
    self.cpsView.delegate = self;
    self.cpsView.selectColor = [UIColor redColor];
    self.cpsView.unSelectColor = [UIColor blackColor];
    self.tableView1 = [UITableView  new];
    self.tableView1.backgroundColor = [UIColor cyanColor];
    self.tableView1.delegate = self;
    self.tableView1.dataSource = self;
    
    
    self.tableView2 = [UITableView new];
    self.tableView2.backgroundColor = [UIColor cyanColor];
    self.tableView2.delegate = self;
    self.tableView2.dataSource = self;
    self.cpsView.items = [NSMutableArray arrayWithArray:@[self.tableView1,self.tableView2]];
    [self.cpsView addContentItems:self.cpsView.items Titles:@[@"量化收益", @"今日排行",]];
    [_bottomTitleView addSubview:self.cpsView];
    [self.cpsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(_bottomTitleView);
    }];
    
}

- (void)buttonView:(CPSpinnerButtonView *)buttonView didSelectItem:(NSNumber*)index{
    NSLog(@"%@-----%@", buttonView, index);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

#pragma mark UITableViewDelegate UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.tableView1) {
        return self.dataArray.count;
    }else{
        return self.markArray.count;
        
    }
    
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView1) {
        IncomeCell *cell = [tableView dequeueOrInitCellWithNibName:@"IncomeCell" identifier:@"IncomeCell"];
        cell.model = self.dataArray[indexPath.row];
        return cell;
    }if (tableView == self.tableView2) {
        DayRankCell *cell = [tableView dequeueOrInitCellWithNibName:@"DayRankCell" identifier:@"DayRankCell"];
        cell.dayRankModel = self.markArray [indexPath.row];
        return cell;
        
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView1) {
                DetailController * detailVC = [[DetailController alloc]init];
        detailVC.incomeArray = self.dataArray;
        detailVC.index  = indexPath.row;
        [self presentViewController:detailVC animated:YES completion:nil];
    }
    if (tableView == self.tableView2) {
        
        DetailController * detailVC = [[DetailController alloc]init];
        detailVC.rankArray = self.markArray;
        detailVC.index  = indexPath.row;
        [self presentViewController:detailVC animated:YES completion:nil];
    }
    
    
    
//    DetailViewController *detailVC =[[DetailViewController alloc]init];
//    [self.navigationController pushViewController:detailVC animated:YES];
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    // 自定义头视图
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    
    
    UILabel *lable1 = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 4, 10, SCREEN_WIDTH/4, 20)];
    lable1.font = [UIFont systemFontOfSize:13];
    lable1.textAlignment = NSTextAlignmentCenter;
    
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2, 10, 1, 20)];
    view1.backgroundColor = [UIColor grayColor];
    
    UILabel *lable2 = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH /2 +1 , 10, SCREEN_WIDTH/4, 20)];
    lable2.textAlignment = NSTextAlignmentCenter;
    lable2.font = [UIFont systemFontOfSize:13];
    
    
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 4 *3 +1, 10, 1, 20)];
    view2.backgroundColor = [UIColor grayColor];
    
    
    UILabel *lable3 = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 4 * 3 +2, 10, SCREEN_WIDTH/ 4, 20)];
    lable3.textAlignment = NSTextAlignmentCenter;
    lable3.font = [UIFont systemFontOfSize:13];
   

    [view addSubview:lable1];
    [view addSubview:lable2];
    [view addSubview:lable3];
    [view addSubview:view1];
    [view addSubview:view2];
    lable1.textAlignment = NSTextAlignmentCenter;
    lable2.textAlignment = NSTextAlignmentCenter;
    lable3.textAlignment = NSTextAlignmentCenter;
    if (tableView == self.tableView1) {
        lable1.text = @"年化收益";
        lable2.text = @"胜率";
        lable3.text = @"量化指数";
        
    }if (tableView == self.tableView2) {
        lable1.text = @"最新";
        lable2.text = @"涨跌";
        lable3.text = @"量化指数";
    }
//    [lable1 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo (view).mas_offset(10);
//        make.left.equalTo(view).mas_offset(120);
//        
//    }];
//    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view).mas_offset(10);
//        make.width.mas_equalTo(1);
//        make.left.equalTo(lable1.mas_right).mas_offset(25);
//        make.height.mas_equalTo(20);
//        
//    }];
//    [lable2 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo (view).mas_offset(10);
//        make.left.equalTo(view1.mas_right).mas_offset(25);
//        
//    }];
//    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(view).offset(10);
//        make.left.equalTo(lable2.mas_right).mas_offset(25);
//        make.width.mas_equalTo(1);
//        make.height.mas_equalTo(20);
//    }];
//    [lable3 mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo (view).mas_offset (10);
//        make.right.equalTo (view).mas_offset (-20);
//        make.left.equalTo(view2.mas_right).offset(25);
//        
//    }];
    
    
    view.backgroundColor = [UIColor whiteColor];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (tableView == self.tableView1) {
        return 40;
        
    }else{
        return 40;
    }
}

//开始拖拽
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.startPoint = scrollView.contentOffset;
    
}
//正在滚动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    self.endPiont = scrollView.contentOffset;
    
    CGFloat heightY = CGRectGetMinY(self.bottomTitleView.frame);
    if (self.startPoint.y - self.endPiont.y < -180) {
        NSLog(@"%.f",heightY);
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.view.frame;
            
            frame.origin.y =  64 - heightY;
            frame.size.height += heightY;
            
            self.view.frame = frame;
            
        }];
        
    }
    if (self.startPoint.y - self.endPiont.y > 80) {
        
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.view.frame;
            frame.origin.y =  64;
            
            frame.size.height = frame.size.height - heightY;
            self.view.frame = frame;
            
            
        }];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
